package com.autoagent.ai_live_master.scriptGeneration.controller;

import com.autoagent.ai_live_master.common.base.ApiResponse;
import com.autoagent.ai_live_master.common.base.UserContext;
import com.autoagent.ai_live_master.common.model.PageRequestVO;
import com.autoagent.ai_live_master.common.utils.BeanConverter;
import com.autoagent.ai_live_master.scriptGeneration.dto.ProductMaterialDTO;
import com.autoagent.ai_live_master.scriptGeneration.entity.ProductMaterialFile;
import com.autoagent.ai_live_master.scriptGeneration.service.ProductMaterialsService;
import com.autoagent.ai_live_master.scriptGeneration.vo.ProductMaterialUploadVO;
import com.autoagent.ai_live_master.scriptGeneration.vo.SearchRequestVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Tag(name = "13-产品素材管理", description = "产品素材的上传和检索相关接口")
@RestController
@RequestMapping("/product-materials")
public class ProductMaterialsController {

    @Autowired
    private ProductMaterialsService productMaterialsService;

    @Operation(summary = "上传产品相关素材文件", description = "上传产品素材文件到知识库")
    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    public ApiResponse<String> add(
            @Parameter(description = "上传文件信息", required = true)
            @ModelAttribute ProductMaterialUploadVO uploadVO) {
        try {
            Long currentUserId = UserContext.getCurrentUserId();
            log.info("开始处理文件上传请求 - 用户ID: {}, 知识库ID: {}, 文件名: {}", 
                currentUserId,
                uploadVO.getKbId(),
                uploadVO.getFile().getOriginalFilename());
            Long kbId = uploadVO.getKbId();
            if (kbId == null) {
                uploadVO.setKbId(2978L);
            }

            ProductMaterialDTO uploadDTO = BeanConverter.convert(uploadVO, ProductMaterialDTO.class);
            uploadDTO.setUserId(currentUserId);
            
            productMaterialsService.addMaterial(uploadDTO);
            
            log.info("文件上传成功 - 用户ID: {}", currentUserId);
            return ApiResponse.success("文件上传成功");
        } catch (Exception e) {
            log.error("文件上传失败 - 错误信息: {}", e.getMessage(), e);
            return ApiResponse.error(500, "文件上传失败: " + e.getMessage());
        }
    }

    @Operation(summary = "搜索产品素材", description = "根据查询内容搜索产品素材")
    @PostMapping(value = "/search")
    public ApiResponse<String> search(
            @Parameter(description = "搜索查询内容", required = true)
            @RequestBody SearchRequestVO query) {
        try {
            log.info("开始检索产品信息 - 查询字符串: {}", query.getQuery());
            String results = productMaterialsService.searchProductMaterials(query.getQuery());
            log.info("检索成功 - 结果数量: {}", results);
            return ApiResponse.success(results);
        } catch (Exception e) {
            log.error("检索失败 - 错误信息: {}", e.getMessage(), e);
            return ApiResponse.error(500, "检索失败: " + e.getMessage());
        }
    }
    @Operation(summary = "分页查询当前用户的产品素材")
    @PostMapping("/list")
    public ApiResponse<Page<ProductMaterialFile>> list(@Validated @RequestBody PageRequestVO pageRequestVO) {
        try {
            Long currentUserId = UserContext.getCurrentUserId();
            log.info("开始分页查询用户的产品素材列表 - 用户ID: {}, pageNum: {}, pageSize: {}, keyword: {}",
                    currentUserId,
                    pageRequestVO.getPageNum(),
                    pageRequestVO.getPageSize(),
                    pageRequestVO.getKeyword());

            Page<ProductMaterialFile> result = productMaterialsService.getDatasetsByUserId(
                    currentUserId,
                    pageRequestVO.getPageNum(),
                    pageRequestVO.getPageSize(),
                    pageRequestVO.getKeyword());

            log.info("分页查询成功 - 用户ID: {}, 返回记录数: {}, 总数: {}",
                    currentUserId,
                    result.getRecords().size(),
                    result.getTotal());

            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("分页查询用户的产品素材列表失败 - 错误信息: {}", e.getMessage(), e);
            return ApiResponse.error(500, "查询失败：" + e.getMessage());
        }
    }

    @Operation(summary = "删除产品素材记录", description = "删除产品素材，包括知识库数据集、OSS文件和数据库记录")
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteMaterial(@Parameter(description = "素材记录ID", required = true)
                                              @PathVariable Long id) {
        try {
            productMaterialsService.deleteMaterial(id);
            return ApiResponse.success("删除成功");
        } catch (Exception e) {
            log.error("删除产品素材失败 - ID: {}, 错误: {}", id, e.getMessage(), e);
            return ApiResponse.error(500, "删除失败：" + e.getMessage());
        }
    }
}